package cn.android666.audiorecorder.pcm

import cn.android666.audiorecorder.objectpool.ByteBufferPool
import timber.log.Timber
import java.nio.ByteBuffer
import java.util.concurrent.ArrayBlockingQueue
import java.util.concurrent.TimeUnit
import java.util.concurrent.atomic.AtomicBoolean

class PCMSaveThread(pcmByteBufferPool: ByteBufferPool) : PCMProcessThread(pcmByteBufferPool) {

    private val pcmSaver = PCMSaver()
    private val pcmQueue  = ArrayBlockingQueue<ByteBuffer>(3)
    private var needRun = AtomicBoolean(true)


    override fun addPcmToQueue(byteBuffer: ByteBuffer) {
        val isSuccess = pcmQueue.offer(byteBuffer)
        if (!isSuccess) {
            Timber.e("保存pcm时队列装不下了，丢帧")
        }
    }


    override fun run() {
        android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_AUDIO)
        while (needRun.get()) {
            pcmQueue.poll(30L, TimeUnit.MILLISECONDS)?.let { byteBuffer ->
                pcmSaver.write(byteBuffer )
                pcmByteBufferPool.returnObject(byteBuffer)
            }
        }
        pcmSaver.close()
    }

    override fun close() {
        needRun.set(false)
    }

}